<template>
  <el-dialog v-model="dialogVisible" title="权限设置" width="500" :before-close="handleClose">
    <el-tree
      v-if="dialogVisible"
      style="max-width: 600px"
      :data="tree"
      show-checkbox
      node-key="name"
      :default-expanded-keys="defaultExpandedKeys"
      :default-checked-keys="defaultCheckedKeys"
      :props="defaultProps"
      @check="handleCheck"
    />
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose(false)">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { permissionView, permissionSave } from "@/api/user/index.api";
import useToggle from "@/hooks/useToggle";

// const emit = defineEmits(["refresh"]);

const [dialogVisible, _, setDialogVisible] = useToggle();

const handleClose = () => setDialogVisible(false);
const username = ref("");
const handleOpen = (e) => {
  username.value = e;
  setDialogVisible(true);
  getTree(e);
};

const defaultProps = {
  children: "children",
  label: "label",
};
const tree = ref([]);
const defaultExpandedKeys = ref([]);
const defaultCheckedKeys = ref([]);
const getTree = (username) => {
  permissionView({ username }).then((res) => {
    tree.value = res?.children;
    defaultExpandedKeys.value = res?.children?.map((item) => item.name);
    traverseTree(res.children, (item) => {
      if (item.checked && item.children.length === 0) {
        defaultCheckedKeys.value.push(item.name);
      }
    });
  });
};

const handleCheck = (_, e) => {
  const { checkedKeys } = e;
  traverseTree(tree.value, (item) => {
    if (checkedKeys.includes(item.name)) return (item.checked = true);
    item.checked = false;
  });
};

const traverseTree = (tree, callback) => {
  for (let i = 0; i < tree.length; i++) {
    const child = tree[i];
    callback && callback(child);
    if (child.children && child.children.length > 0) {
      child.children = traverseTree(child.children, callback);
    }
  }

  return tree;
};

const submit = () => {
  permissionSave({
    username: username.value,
    tree: {
      children: tree.value,
    },
  }).then(() => {
    tree.value = [];
    defaultCheckedKeys.value = [];
    defaultExpandedKeys.value = [];
    setDialogVisible(false);
    ElMessage({
      message: "保存成功",
      type: "success",
    });
  });
};

defineExpose({
  handleOpen,
});
</script>
